package com.xkdx.guangguang.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import android.util.Log;

public class IOUtils {
	
	/**
	 *<p>InputStream2ByteArray</p><br/>
	 * @since 2.0
	 * @author lihl
	 * @param input
	 * @return
	 * @throws IOException
	 */
	public static byte[] fromStringtoByteArray(String inputStr) throws IOException {
		ByteArrayInputStream input = new ByteArrayInputStream(inputStr.getBytes());
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		copy(input, output);
		byte[] b = output.toByteArray();
		output.close();
		return b;
	}
	
	private static int copy(InputStream input, OutputStream output) throws IOException {
		long count = copyLarge(input, output);
		if (count > 2147483647L) {
			return -1;
		}
		return (int) count;
	}
	
	private static long copyLarge(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[4096];
		long count = 0L;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
			Log.d("lhl",String.valueOf(count));
		}
		return count;
	}
	
	public static String forInputStreamToString(InputStream data) throws Exception {
		String str = null;
		BufferedReader r = null;
		StringBuffer sb = new StringBuffer();

		try {
			r = new BufferedReader(new InputStreamReader(data));

			String line;
			while ((line = r.readLine()) != null) {
				sb.append(line);
			}
			str = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		return str;
	}
}
